$(document).ready(function() {
	SB.FriendBillModel = Backbone.Model.extend({
		defaults : {
			"amount" : 0,
		}		
	});

	SB.FriendBillView = Backbone.View.extend({
		tagName : "tr",
		className : 'friend-bill',
		template : _.template($('#new-friend-bill-tpl').html()),

		initialize : function() {
			_.bindAll(this, 'render', 'setBillAmount', 'remove');
			this.model.on('change', this.render);
		},

		events : {
			'keyup #amount' : 'setBillAmount',
			'click #remove' : 'remove'
		},

		remove : function() {
			SB.Events.trigger('SB.REMOVE_FRIEND_BILL', this.$('#remove').attr('data-seq'));
		},

		setBillAmount : function() {
			// Validate the amount
			amount = this.$('#amount').val();
			if ($.isNumeric(amount)) {
				this.$('#amount').tooltip('hide');
				var seq = this.$('#remove').attr('data-seq');
				var friendBill = SB.friendBillCollection.at(seq);
				friendBill.set({
					amount : amount
				});
			} else {
				this.$('#amount').tooltip('show');
			}
		},

		render : function() {
			$(this.el).html(this.template(this.model.toJSON()));

			// Setup tooltip when the html has rendered
			this.$('#amount').tooltip({
				trigger : 'manual',
				title : 'Please enter number only'
			});

			return this;
		}
	});

	SB.FriendBillCollection = Backbone.Collection.extend({
		model : SB.FriendBillModel
	});
	SB.friendBillCollection = new SB.FriendBillCollection();

	SB.FriendBillCollectionView = Backbone.View.extend({
		tagName : 'table',
		className : 'table table-striped wrap-txt',

		initialize : function() {
			_.bindAll(this, 'render', 'addOne', 'removeOne');

			// Reset view when emails changes
			SB.friendBillCollection.on('reset', this.render);
			SB.friendBillCollection.on('add', this.addOne);
			SB.friendBillCollection.on('remove', this.removeOne);
		},

		render : function() {
			$(this.el).html('');
			return this;
		},

		addOne : function(model) {
			var friendView = new SB.FriendBillView({
				model : model
			});
			$(this.el).append(friendView.render().el);
		},

		// Remove
		removeOne : function(model) {
		}
	});

	/******************************************************************************************************************
	 *
	 */

	SB.NewBillModel = Backbone.Model.extend({
		defaults : {
			"total_amount" : 0,
			"title" : "",
			"message" : ""
		}
	});

	SB.newBillModel = new SB.NewBillModel();
	
	SB.PreView = Backbone.View.extend({
		className: 'modal fade hide',
		id: "myModal",
		template : _.template($('#preview-new-bill-tpl').html()),
		
		render: function() {
			$(this.el).html(this.template(this.model.toJSON()));
			console.log(this.el);
			return this;
		}
	});

	SB.NewBillView = Backbone.View.extend({
		className : 'span7 new-bill',

		template : _.template($('#new-bill-tpl').html()),

		initialize : function() {
			_.bindAll(this, 'render', 'parseEmails', 'removeBill', 'validateNumber', 'preview');
			// Reset view when total amount changes
			SB.newBillModel.on('change', this.parseEmails);
			SB.Events.on('SB.REMOVE_FRIEND_BILL', this.removeBill);
		},

		events : {
			'blur #emails' : 'parseEmails',
			'keyup #total-amount' : 'validateNumber',
			'click #preview' : "preview"
		},

		validateNumber : function() {
			$('#total-amount').tooltip({
				trigger : 'manual',
				title : 'Please enter number only'
			});

			var total_amount = this.$('#total-amount').val();
			console.log(total_amount);
			if ($.isNumeric(total_amount)) {
				this.$('#total-amount').tooltip('hide');
				SB.newBillModel.set({
					total_amount : total_amount
				});
			} else {
				console.log('non numeric');
				this.$('#total-amount').tooltip('show');
				SB.newBillModel.set({
					total_amount : 0
				});
			}
		},

		parseEmails : function() {
			// Reset views
			SB.friendBillCollection.reset();
			var invalidEmail = false;

			// Add model to collection
			var friends = goog.format.EmailAddress.parseList(this.$('#emails').val());
			for ( i = 0; i < friends.length; i++) {
				var friend = friends[i];

				// Only render if user enter valid email address
				if (!friend.getAddress() || friend.getAddress() == "") {
					invalidEmail = true;
					continue;
				}

				// Set model attributes
				var friendModel = new SB.FriendBillModel();
				friendModel.set({
					name : friend.getName(),
					email : friend.getAddress(),
					amount : SB.newBillModel.get('total_amount') / friends.length,
					seq : i
				});
				// If name is not included, just extract the alias
				if (friendModel.get('name') == "" || friendModel.get('name') == " ") {
					var name = friendModel.get('email').split('@')[0];
					friendModel.set({
						name : name
					});
				}

				// Update collections
				SB.friendBillCollection.add(friendModel);
			}

			if (invalidEmail) {
				this.$('#emails').tooltip('show');
			} else {
				this.$('#emails').tooltip('hide');
			}
		},

		render : function() {
			$(this.el).html(this.template());

			// Construct child views
			SB.friendCollectionView = VM.createView("friendCollectionView", function() {
				return new SB.FriendBillCollectionView();
			});
			this.$('#friend-bills').append(SB.friendCollectionView.render().el);

			// Configure plugins when elements are ready
			this.$('#emails').tooltip({
				trigger : 'manual',
				title : 'One or more emails is invalid'
			});

			return this;
		},

		removeBill : function(index) {
			// Remove model from collection
			var model = SB.friendBillCollection.at(index);
			SB.friendBillCollection.remove(model);

			// Reset text inside the emails textarea
			var text = '';
			for (var i = 0; i < SB.friendBillCollection.length; i++) {
				var friend = SB.friendBillCollection.at(i);
				text += friend.get('name') + ' <' + friend.get('email') + '>,';
			}
			this.$('#emails').val(text);

			// Reset all views
			this.parseEmails();
			this.$('#emails').trigger('oninput');
			// For IE
			this.$('#emails').trigger('onpropertychange');
		},

		preview : function() {
			// Prepare data to submit
			SB.newBillModel.set({
				title : this.$('#title').val(),
				message : this.$('#message').val(),
				total_amount : this.$('#total-amount').val(),
				remind_freq : this.$('#remind-freq').val(),
				friend_bills : JSON.stringify(SB.friendBillCollection.toJSON())
			});

			SB.preView = VM.createView("preView", function(){
				return new SB.PreView({model: SB.newBillModel});
			});
			SB.preView.render();
			$(SB.preView.el).modal('show');
			SB.preView.$('#send').click(this.submit);
		},
		
		submit: function() {
			console.log("submit to server");
			$.post('/api/bill/create/', SB.newBillModel.toJSON(), function(data) {
				SB.createdBills = JSON.parse(data);
				SB.billCollection.reset(SB.createdBills);
				$(SB.preView.el).modal('hide');
				SB.router.navigate('sent', {trigger: true});
			});
		}
	});
});
